package me.boot.db.redis;

import lombok.extern.slf4j.Slf4j;
import me.boot.db.redis.beans.RedisOps;
import me.boot.db.redis.cache.CacheProps;
import me.boot.db.redis.serializer.RedisObjectSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年10月20日 5:05 下午
 */
@Slf4j
@ComponentScan("me.boot.redis")
@EnableConfigurationProperties({CacheProps.class})
@Configurable
public class RedisConfiguration {

    @Autowired
    CacheProps cacheProps;

    @PostConstruct
    void init() {
        log.info("Init RedisConfiguration");
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory factory) {
        return new StringRedisTemplate(factory);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        setSerializer(factory, template, new RedisObjectSerializer());
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisOps redisOps(RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) {
        return new RedisOps(redisTemplate, stringRedisTemplate, cacheProps.getDef().isCacheNullValues());
    }


    private void setSerializer(RedisConnectionFactory factory, RedisTemplate<String, Object> template, RedisSerializer<Object> redisSerializer) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(redisSerializer);
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(redisSerializer);
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
    }

}
